package com.info.zhiduoduo.common.utils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 使用简单的AES加密方式的加解密工具类
 */
public class AesUtil {

	/**
	 * 加密明文
	 *
	 * @param data 明文
	 * @param key  加密key
	 * @return 加密后的密文
	 * @throws Exception
	 */
	public static String encrypt(String data, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
		return Base64.getEncoder().encodeToString(encrypted);//此处使用BASE64做转码。
	}

	/**
	 * 解密密文
	 *
	 * @param data 密文
	 * @param key  加密key
	 * @return 解密后的明文
	 * @throws Exception
	 */
	public static String decrypt(String data, String key) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] encrypted1 = Base64.getDecoder().decode(data);//先用base64解密
		byte[] original = cipher.doFinal(encrypted1);
		String originalString = new String(original, StandardCharsets.UTF_8);
		return originalString;
	}

	public static void main(String[] args) throws Exception {
		String key = RandomUtil.getRandomStr(16);
		String content = "{\"result\": \"1\"}";
		String encrypt = encrypt(content, key);
		System.out.println("encrypt:" + encrypt);
		String decrypt = decrypt(encrypt, key);
		System.out.println("decrypt:" + decrypt);
	}
}
